package com.nineclock.system.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.entity.Result;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.oss.service.OSSService;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.common.utils.UUIDUtils;
import com.nineclock.system.dto.SysChangeMainManagerDTO;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.mapper.SysCompanyMapper;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysCompanyUserRoleMapper;
import com.nineclock.system.mapper.SysRoleMapper;
import com.nineclock.system.pojo.SysCompany;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysCompanyUserRole;
import com.nineclock.system.pojo.SysRole;
import com.nineclock.system.service.SysCompanyService;
import com.nineclock.system.service.SysCompanyUserService;
import com.nineclock.system.service.SysSmsService;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.util.Map;

@Service
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements SysCompanyService {

    @Autowired
    private SysCompanyUserMapper sysCompanyUserMapper;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;


    /**
     * 查询当前企业信息
     *
     * @return
     */
    @Override
    public SysCompany queryCompanyInfo() {
        //判断是否登录
        if (CurrentUserHolder.get() == null) {
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }
        //参数判断
        Long companyId = CurrentUserHolder.get().getCompanyId();

        if (companyId == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        SysCompany sysCompany = this.getById(companyId);
        if (sysCompany == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        return sysCompany;
    }

    /**
     * 上传图片
     *
     * @return
     */

    @Autowired
    private OSSService ossService;

    @Override
    public String uploadOSS(MultipartFile multipartFile) {
        //1.参数判断
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }

        //检查文件类型是否符合要求
        String contentType = multipartFile.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(contentType)) {
            throw new NcException(ResponseEnum.INVALID_FILE_TYPE);
        }

        //检查文件大小是否超过限制
        long fileSize = multipartFile.getSize();
        if (fileSize > NcConstant.maxFileSize) {
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }
        //判断是否登录
        if (CurrentUserHolder.get() == null) {
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }

        //获取原始文件名
        String originalFilename = multipartFile.getOriginalFilename();

        //在原始文件名基础上生成唯一的文件名  UUID+原始文件名的后缀
        String prefix = UUIDUtils.getUUID();
        int lastIndex = originalFilename.lastIndexOf(".");
        String postfix = originalFilename.substring(lastIndex);
        String fileName = prefix + postfix;

        //上传图片
        try {
            String url = ossService.uploadImgFile("", fileName, multipartFile.getInputStream());
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            throw new NcException(ResponseEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 修改企业基本信息
     *
     * @param map
     * @return
     */
    @Override
    public void modifyCompanyInfo(Map<String, String> map) {


        //参数校验
        if (Collections.isEmpty(map)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //判断是否登录
        if (CurrentUserHolder.get() == null) {
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }

        Long companyId = CurrentUserHolder.get().getCompanyId();
        if (companyId == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        SysCompany sysCompany = this.getById(companyId);
        if (sysCompany == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }

        //更新企业信息
        try {
            sysCompany.setName(map.get("name"));
            sysCompany.setLogo(map.get("logo"));
            this.updateById(sysCompany);
        } catch (Exception e) {
            e.printStackTrace();
            throw new NcException(ResponseEnum.UPDATE_OPERATION_FAIL);
        }
    }

    /**
     * 获取企业当前主管理员
     *
     * @return
     */
    @Override
    public SysCompanyUser getCurrentAdmin() {

        Long companyId = CurrentUserHolder.get().getCompanyId();
        SysCompanyUser currentAdmin = sysCompanyMapper.getCurrentAdmin(companyId);
        if (currentAdmin == null) {
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }
        return currentAdmin;
    }


    /**
     * 更改系统管理员
     */
    @Autowired
    private SysCompanyUserService sysCompanyUserService;

    @Autowired
    private SysSmsService sysSmsService;

    @Autowired
    private SysCompanyUserRoleMapper sysCompanyUserRoleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Override
    public void updateAdmin(SysChangeMainManagerDTO dto) {
        //1.判断参数合法性
        if (dto == null || StrUtil.isEmpty(dto.getCode()) || dto.getUserId() == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        Long companyId = CurrentUserHolder.get().getCompanyId(); //当前登录员工的公司

        //新的管理员公司的员工ID   就是companyUser的id
        Long companyUserIdNew = dto.getUserId();

        //2.根据新用户ID查询是否存在
        SysCompanyUser sysCompanyUser = sysCompanyUserService.getById(companyUserIdNew);
        if (sysCompanyUser == null) {
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //校验验证码
        String redisKey = SMSConstant.SMS_CHANGE_MANAGER_KEY_PREFIX + sysCompanyUser.getMobile();
        String redisCode = stringRedisTemplate.opsForValue().get(redisKey);
        if (!redisCode.equals(dto.getCode())) {
            //如果验证码错误抛异常
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        //根据公司的id查询管理员角色对应的id
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRole::getCompanyId, companyId);
        lambdaQueryWrapper.eq(SysRole::getRoleName, NcConstant.ADMIN_ROLE_SYS);

        SysRole sysRole = sysRoleMapper.selectOne(lambdaQueryWrapper);
        //获取管理员角色的id  必须动态获取不然改了表以后管理的角色会变
        Long roleId = sysRole.getId();

        //获取原管理员信息
        SysCompanyUser oldAdmin = getCurrentAdmin();

        //删除旧的管理员与公司的关系
        LambdaQueryWrapper<SysCompanyUserRole> lambdaQueryWrapperForDelete = new LambdaQueryWrapper<>();
        lambdaQueryWrapperForDelete.eq(SysCompanyUserRole::getCompanyId, companyId);
        lambdaQueryWrapperForDelete.eq(SysCompanyUserRole::getCompanyUserId, oldAdmin.getId());  //旧管理员的员工id
        lambdaQueryWrapperForDelete.eq(SysCompanyUserRole::getRoleId, roleId);
        sysCompanyUserRoleMapper.delete(lambdaQueryWrapperForDelete);


        //添加新的系统管理员与员工的关系
        //封装一个SysCompanyUserRole类对象
        SysCompanyUserRole sysCompanyUserRole = new SysCompanyUserRole();
        sysCompanyUserRole.setRoleId(roleId);
        sysCompanyUserRole.setCompanyId(companyId); //设置公司id
        sysCompanyUserRole.setCompanyUserId(dto.getUserId());  //设置员工id
        int result = sysCompanyUserRoleMapper.insert(sysCompanyUserRole);

        //如果插入返回值为0 则抛异常
        if (result == 0) {
            throw new NcException(ResponseEnum.INSERT_OPERATION_FAIL);
        }

        //删除redis
        stringRedisTemplate.delete(redisKey);
    }
}
